package cn.kys.modules.system.controller;

import cn.kys.logging.aop.log.EnableKysLog;
import cn.kys.modules.system.domain.Dept;
import cn.kys.modules.system.domain.vo.Result;
import cn.kys.modules.system.pojo.LayerDto;
import cn.kys.modules.system.pojo.SubtaskGeom;
import cn.kys.modules.system.pojo.SubtaskVo;
import cn.kys.modules.system.service.TaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.locationtech.jts.io.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/task_api")
@Api(tags = {"业务——任务分配模块"})
public class TaskApi {
    @Autowired
    private TaskService taskService;
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    //获取所有外业人员列表
    @GetMapping("/getUsers")
    public Map getUsers(@RequestParam("roleStr") String roleStr) {
        Map returnMap = new HashMap();
        try {
            List list = taskService.getUsers(roleStr);
            returnMap.put("data", list);
            returnMap.put("success", true);
            returnMap.put("resMsg", "获取成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("success", false);
            returnMap.put("resMsg", "异常");
        }
        return returnMap;
    }

    //获取所有人员列表-根据任务id
    @GetMapping("/getUsersByTaskId")
    public Map getUsersByTaskId(@RequestParam("taskid") String taskid) {
        Map returnMap = new HashMap();
        try {
            List list = taskService.getUsersByTaskId(taskid);
            returnMap.put("data", list);
            returnMap.put("success", true);
            returnMap.put("resMsg", "获取成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("success", false);
            returnMap.put("resMsg", "异常");
        }
        return returnMap;
    }

    //获取所有人员列表-根据任务id
    /**
     * @Author zhaoxw
     * @Description //TODO
     * @Date 13:29 2024/4/12
     * @return
     **/
    @ApiOperation("PC端——zxw获取所有人员列表-根据任务id")
    @GetMapping("/getUsersByTaskIdPc")
    public Result getUsersByTaskIdPc(@RequestParam("taskid") Integer taskid) throws IOException, ParseException {
        List<SubtaskVo> list = taskService.getUsersByTaskIdPc(taskid);
        return Result.success(list);
    }


    @GetMapping("/getAllTasks")
    public Map getAllTasks() {
        Map returnMap = new HashMap();
        try {
            List list = taskService.getAllTasks();
            returnMap.put("data", list);
            returnMap.put("success", true);
            returnMap.put("resMsg", "获取成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("success", false);
            returnMap.put("resMsg", "异常");
        }
        return returnMap;
    }

    @EnableKysLog("获得任务中所有已提交和未提交的图斑数")
    @ApiOperation("获得任务中所有已提交和未提交的图斑数")
    @GetMapping(value = "/getFinishAndUnFinishTaskNum")
    public Result getFinishAndUnFinishTaskNum() {
        List<Integer> result = taskService.getFinishAndUnFinishTaskNum();
        return Result.success(result);
    }


    @GetMapping("/getTasksByParam")
    public Map getTasksByParam(@RequestParam("is_public") boolean is_public) {
        Map returnMap = new HashMap();
        try {
            List list = taskService.getTasksByParam(is_public);
            returnMap.put("data", list);
            returnMap.put("success", true);
            returnMap.put("resMsg", "获取成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("success", false);
            returnMap.put("resMsg", "异常");
        }
        return returnMap;
    }

    //新建任务
    @GetMapping("/addTask")
    public Map addTask(@RequestParam("name") String name, @RequestParam("caseid") int caseid, @RequestParam("casename") String casename, @RequestParam("is_public") boolean is_public, @RequestParam("lat") String lat, @RequestParam("lon") String lon) {
        Map returnMap = new HashMap();
        try {
            Map map = taskService.addTask(name, caseid, casename, is_public, lat, lon);
            returnMap.put("data", map);
            returnMap.put("success", true);
            returnMap.put("resMsg", "获取成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("success", false);
            returnMap.put("resMsg", "异常");
        }
        return returnMap;
    }

    //编辑任务状态
    @GetMapping("/editTaskStatus")
    public Map editTaskStatus(@RequestParam("id") String id, @RequestParam("status") String status) {
        Map returnMap = new HashMap();
        try {
            Map map = taskService.editTaskStatus(id, status);
            returnMap.put("data", map);
            returnMap.put("success", true);
            returnMap.put("resMsg", "获取成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("success", false);
            returnMap.put("resMsg", "异常");
        }
        return returnMap;
    }

    @ApiOperation("统计任务中未提交的任务数")
    @GetMapping("/countUncommit")
    public Map countUncommit(@RequestParam("taskid") Integer taskid) {
        Map returnMap = new HashMap();
        try {
            Long count = taskService.countUncommit(taskid);
            returnMap.put("data", count);
            returnMap.put("success", true);
            returnMap.put("resMsg", "获取成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("success", false);
            returnMap.put("resMsg", "异常");
        }
        return returnMap;
    }


    //编辑地块状态
    @GetMapping("/editPolygonStatus")
    public Map editPolygonStatus(@RequestParam("subtaskPolygonId") String subtaskPolygonId, @RequestParam("status") String status) {
        Map returnMap = new HashMap();
        try {
            taskService.editPolygonStatus(subtaskPolygonId, status);
            returnMap.put("success", true);
            returnMap.put("resMsg", "获取成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("success", false);
            returnMap.put("resMsg", "异常");
        }
        return returnMap;
    }

    //绑定用户
    @GetMapping("/addTaskUsers")
    public Map addTaskUsers(@RequestParam("taskid") String taskid, @RequestParam("userJson") String userJson) {
        Map returnMap = new HashMap();
        try {
            taskService.addTaskUsers(taskid, userJson);
            returnMap.put("success", true);
            returnMap.put("resMsg", "获取成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("success", false);
            returnMap.put("resMsg", "异常");
        }
        return returnMap;
    }

    //编辑任务内容
    @GetMapping("/editTaskContent")
    public Map editTaskContent(@RequestParam("id") String id, @RequestParam("name") String name, @RequestParam("caseid") int caseid, @RequestParam("casename") String casename, @RequestParam("is_public") boolean is_public, @RequestParam("lat") String lat, @RequestParam("lon") String lon) {
        Map returnMap = new HashMap();
        try {
            Map map = taskService.editTaskContent(id, name, caseid, casename, is_public, lat, lon);
            returnMap.put("data", map);
            returnMap.put("success", true);
            returnMap.put("resMsg", "获取成功");
        } catch (Exception e) {
            returnMap.put("success", false);
            returnMap.put("resMsg", "异常");
        }
        return returnMap;
    }

    //获取图层的矢量瓦片
    @GetMapping("/getMVTByLayerName/**/**/**.pbf")
    public void getMVTByLayerName(@RequestParam("layername") String layername, @RequestParam("tileName") String tileName) {
        String fileURL = request.getRequestURL().toString();
        String[] fileURLArr = fileURL.split("/");
        int length = fileURLArr.length;
        int x = Integer.valueOf(fileURLArr[length - 2]).intValue();
        int z = Integer.valueOf(fileURLArr[length - 3]).intValue();
        int y = Integer.valueOf(fileURLArr[length - 1].split("\\.")[0]).intValue();


        Map map = taskService.getMVTByLayerName(layername, tileName, x, y, z);
        response.setHeader("Content-Type", "application/x-protobuf");
        try {
            OutputStream res = response.getOutputStream();
            byte[] bt = (byte[]) map.get("mvt");
            if (bt != null & bt.length > 0) {
                res.write(bt);
                res.flush();
                res.close();
            }
        } catch (org.apache.catalina.connector.ClientAbortException el) {
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
    }

    //获取某一个采集员的矢量瓦片（edit）
    @GetMapping("/getMVTByPerson/**/**/**.pbf")
    public void getMVTByPerson(@RequestParam("subtaskid") String subtaskid, @RequestParam("tileName") String tileName) {
        String fileURL = request.getRequestURL().toString();
        String[] fileURLArr = fileURL.split("/");
        int length = fileURLArr.length;
        int x = Integer.valueOf(fileURLArr[length - 2]).intValue();
        int z = Integer.valueOf(fileURLArr[length - 3]).intValue();
        int y = Integer.valueOf(fileURLArr[length - 1].split("\\.")[0]).intValue();


        Map map = taskService.getMVTByPerson(subtaskid, tileName, x, y, z);
        response.setHeader("Content-Type", "application/x-protobuf");
        try {
            OutputStream res = response.getOutputStream();
            byte[] bt = (byte[]) map.get("mvt");
            if (bt != null & bt.length > 0) {
                res.write(bt);
                res.flush();
                res.close();
            }
        } catch (org.apache.catalina.connector.ClientAbortException el) {
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
    }

    //获取某一个任务的矢量瓦片（task）
    @GetMapping("/getMVTByTask/**/**/**.pbf")
    public void getMVTByTask(@RequestParam("taskid") String taskid, @RequestParam("tileName") String tileName) {
        String fileURL = request.getRequestURL().toString();
        String[] fileURLArr = fileURL.split("/");
        int length = fileURLArr.length;
        int x = Integer.valueOf(fileURLArr[length - 2]).intValue();
        int z = Integer.valueOf(fileURLArr[length - 3]).intValue();
        int y = Integer.valueOf(fileURLArr[length - 1].split("\\.")[0]).intValue();
        Map map = taskService.getMVTByTask(taskid, tileName, x, y, z);
        response.setHeader("Content-Type", "application/x-protobuf");
        try {
            OutputStream res = response.getOutputStream();
            byte[] bt = (byte[]) map.get("mvt");
            if (bt != null & bt.length > 0) {
                res.write(bt);
                res.flush();
                res.close();
            }
        } catch (org.apache.catalina.connector.ClientAbortException el) {
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }

    }


    //获取矢量瓦片(格网)
    @GetMapping("/getMVTByGrid/**/**/**.pbf")
    public void getMVTByGrid(@RequestParam("tileName") String tileName
            , @RequestParam("maxLat") String maxLat
            , @RequestParam("minLat") String minLat
            , @RequestParam("maxLon") String maxLon
            , @RequestParam("minLon") String minLon
            , @RequestParam("metre") String metre) {
        String fileURL = request.getRequestURL().toString();
        String[] fileURLArr = fileURL.split("/");
        int length = fileURLArr.length;
        int x = Integer.valueOf(fileURLArr[length - 2]).intValue();
        int z = Integer.valueOf(fileURLArr[length - 3]).intValue();
        int y = Integer.valueOf(fileURLArr[length - 1].split("\\.")[0]).intValue();
        Map map = taskService.getMVTByGrid(tileName, x, y, z, maxLat, minLat, maxLon, minLon, metre);
        response.setHeader("Content-Type", "application/x-protobuf");
        try {
            OutputStream res = response.getOutputStream();
            byte[] bt = (byte[]) map.get("mvt");
            if (bt != null & bt.length > 0) {
                res.write(bt);
                res.flush();
                res.close();
            }
        } catch (org.apache.catalina.connector.ClientAbortException el) {
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }

    }

    //判断绑定范围
    @GetMapping("/judgeBindingPolygon")
    public Map judgeBingdingPolygon(@RequestParam("taskid") String taskid, @RequestParam("subTaskJson") String subTaskJson) {
        Map returnMap = new HashMap();
        try {
            Map map = taskService.judgeBingdingPolygon(taskid, subTaskJson);
            returnMap.put("data", map);
            returnMap.put("success", true);
            returnMap.put("resMsg", "获取成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("success", false);
            returnMap.put("resMsg", "异常");
        }
        return returnMap;
    }

    //绑定范围
    @GetMapping("/bindingPolygon")
    public Map bindingPolygon(@RequestParam("taskid") String taskid, @RequestParam("subTaskJson") String subTaskJson) {
        Map returnMap = new HashMap();
        try {
            taskService.bingindgPolygonPG(taskid, subTaskJson);
            returnMap.put("success", true);
            returnMap.put("resMsg", "获取成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("success", false);
            returnMap.put("resMsg", "异常");
        }
        return returnMap;
    }

    @GetMapping("/delTaskByIds")
    public Map delTaskById(@RequestParam("ids") String ids) {
        Map returnMap = new HashMap();
        try {
            taskService.delTaskByIds(ids);
            returnMap.put("success", true);
            returnMap.put("resMsg", "获取成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("success", false);
            returnMap.put("resMsg", "异常");
        }
        return returnMap;
    }

    @GetMapping("/findFormContentByCaseId")
    public Map findFormContentByCaseId(@RequestParam("subtaskid") String subtaskid, @RequestParam("edit_geoid") String edit_geoid, @RequestParam("caseid") String caseid) {
        Map returnMap = new HashMap();
        try {
            Map map = taskService.findFormContentByCaseId(subtaskid, edit_geoid, caseid);
            returnMap.put("data", map);
            returnMap.put("success", true);
            returnMap.put("resMsg", "获取成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("success", false);
            returnMap.put("resMsg", "异常");
        }
        return returnMap;
    }

    @GetMapping("/findGeomByPos")
    public Map findGeomByPos(@RequestParam("taskid") String taskid, @RequestParam("subtaskid") String subtaskid, @RequestParam("lon") String lon, @RequestParam("lat") String lat) {
        Map returnMap = new HashMap();
        try {
            Map list = taskService.findGeomByPos(taskid, subtaskid, lon, lat);
            returnMap.put("data", list);
            returnMap.put("success", true);
            returnMap.put("resMsg", "获取成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("success", false);
            returnMap.put("resMsg", "异常");
        }
        return returnMap;
    }


    @GetMapping("/test")
    public Map test() {
        Map returnMap = new HashMap();
        try {

            returnMap.put("success", true);
            returnMap.put("resMsg", "获取成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("success", false);
            returnMap.put("resMsg", "异常");
        }
        return returnMap;
    }

    @PostMapping("/exportShpPolygon")
    public Map exportShpPolygon(HttpServletRequest request, HttpServletResponse response, @RequestParam("subtaskid") String subtaskid) {
        Map returnMap = new HashMap();
        try {

            taskService.exportShpPolygon(request, response, subtaskid);

            returnMap.put("success", true);
            returnMap.put("resMsg", "获取成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("success", false);
            returnMap.put("resMsg", "异常");
        }
        return returnMap;
    }


    /**
     * 查询部门数据
     *
     * @return
     */
    //@RequestMapping(value = "/depts",method = RequestMethod.GET) //指定请求方式为GET
    @GetMapping("/list")
    public Result list(@RequestParam("name") String name, @RequestParam("casename") String casename, @RequestParam("isPublic") boolean isPublic) {
        log.info("查询全部task数据");
        //调用service查询部门数据
//        List taskList =  taskService.list();
        List taskList = taskService.listCondition(name, casename, isPublic);

        return Result.success(taskList);
    }


    @EnableKysLog("采集任务分配显示图斑列表——2024.04.08张所新提出需求")
    @ApiOperation("张所——采集任务分配显示图斑列表(未绑定的)")
    @PostMapping(value = "/showPolygonList")
    public Result showPolygonList(@RequestBody SubtaskGeom subtaskGeom) {
        List<Map> subtaskGeomList = taskService.showPolygonList(subtaskGeom);
        return Result.success(subtaskGeomList);
    }


    @EnableKysLog("采集任务分配显示图斑列表后分配未绑定图斑——2024.04.08张所新提出需求")
    @ApiOperation("采集任务分配显示图斑列表后分配未绑定图斑")
    @PostMapping(value = "/assignUnboundPolygon")
    public Result assignUnboundPolygon(LayerDto layerDto) {
        List<Integer> result = taskService.assignUnboundPolygon(layerDto);
        return Result.success(result);
    }


}

